import React, {useEffect, useRef, useState} from 'react';
import {modulesUrl} from "@/assets/constant/modulesUrl";
import TableList from "@/assets/components/tableList";
import {getServiceParams, hooksSet, imitateAClick, isNotBlank, multiply, toFloat} from "@/assets/utils/utils";
// @ts-ignore
import {useRequest} from "umi";
import {getColumnList} from "@/pages/report/TableConfigList/service";
import {TableConfigColumn} from "@/pages/report/TableConfigList/data";
import {executeSql} from "@/pages/report/ReportList/service";
import {ProColumns} from "@ant-design/pro-table";
import {Report} from "@/pages/report/ReportList/data";
import {Button, DatePicker, Form, Input} from "antd";
import moment from "moment";
import "./details.css";
import {getDateString, getDateStringZero, getYesterdayZero} from "@/assets/utils/dateUtils";
import {RangeValue} from "rc-picker/lib/interface";

const ReportDetails: React.FC<{}> = (props) => {
  const [columns, setColumns] = useState<ProColumns<Report>[]>([]);
  /**
   * 获取tableConfigId
   */
    // @ts-ignore
  const tableConfigId = props.match.params.tableConfigId;
  // @ts-ignore
  const reportId = props.match.params.reportId;
  /**
   * 获取报表名称
   */
    // @ts-ignore
  const name = props.match.params.name;

  // const [requestParams, setRequestParams] = useState();
  const queryInitialValueParams = useRef();
  // 是否首次加载
  const isFirst = useRef(true);
  const [form] = Form.useForm();
  const [searchForm] = Form.useForm();

  const getColumnListRun = useRequest((resolve, reject) => getColumnList({id: tableConfigId}), {
    manual: true,
    onSuccess: (result: any, params: any) => {
      let resultColumns: any = []
      result.forEach(function (column: TableConfigColumn, _: any, index: number) {
        if (column.isQuery === "1" && isNotBlank(column.queryInitialValue)) {
        // if (column.isQuery === "1") {
          if(column.queryType === "3" || column.queryType === "4"){
            // @ts-ignore
            queryInitialValueParams.current = Object.assign({}, queryInitialValueParams.current, {[column.columnName]: column.queryInitialValue?.split(",")})
          }else {
            // @ts-ignore
            queryInitialValueParams.current = Object.assign({}, queryInitialValueParams.current, {[column.columnName]: column.queryInitialValue})
          }
        }
        resultColumns.push({
          title: (column.comment || column.name || column.columnName) + (column.showType == "2" ? "（%）" : ""),
          dataIndex: column.columnName,
          className: "report-table-head",
          hideInForm: true,
          hideInSearch: column.isQuery !== "1" ? true : false,
          hideInTable: column.isShow !== "1" ? true : false,
          renderText: (text: string) => {
            let result;
            switch (column.showType) {
              case "2":
                let textNumber = toFloat(text);
                result = textNumber !== undefined ? multiply(textNumber, 100) : undefined;
                break;
              default:
                result = text;
            }
            return result;
          },
          renderFormItem: () => {
            let result;

            switch (column.queryType) {
              case "3":
                result =
                  <DatePicker.RangePicker
                    showTime
                    name={column.columnName}
                    format="YYYY-MM-DD HH:mm:ss"
                    defaultValue={[moment(getYesterdayZero(), 'YYYY-MM-DD HH:mm:ss'), moment(getDateStringZero(), 'YYYY-MM-DD HH:mm:ss')]}
                    onChange={(values: RangeValue<any>, formatString: [string, string])=>{
                      // @ts-ignore
                      queryInitialValueParams.current = Object.assign({}, queryInitialValueParams.current, {[column.columnName]: formatString})
                    }}
                  />
                break;
              case "4":
                result =
                  <DatePicker.RangePicker
                    name={column.columnName}
                    format="YYYYMMDD"
                    disabledDate={(currentDate) => currentDate && currentDate >= moment(getDateString("yyyyMMdd"), 'YYYYMMDD')}
                    defaultValue={[moment(column.queryInitialValue?.split(",")[0]), moment(column.queryInitialValue?.split(",")[1])]}
                    onChange={(values: RangeValue<any>, formatString: [string, string])=>{
                      // @ts-ignore
                      queryInitialValueParams.current = Object.assign({}, queryInitialValueParams.current, {[column.columnName]: formatString})
                    }}
                  />
                break;
              default:
                result = <Input placeholder={"请输入"} name={column.columnName} style={{width: 300}} onChange={(e)=>{
                  // @ts-ignore
                  queryInitialValueParams.current = Object.assign({}, queryInitialValueParams.current, {[column.columnName]: e.target.value})
                }}/>
            }
            return result
          }
        })
      })
      hooksSet(setColumns, resultColumns);
      params[0]();
    }
  }).run

  useEffect(() => {

  }, []);

  return (
    <TableList
      tableClassName={"report-table"}
      title={name}
      columns={columns}
      form={form}
      searchRef={searchForm}
      moduleUrl={modulesUrl.reportSource}
      isNotCanAdd={true}
      changeColumns={(columns: any) => hooksSet(setColumns, columns)}
      request={(params: any) => {
        if (isFirst.current) {
          // 首次加载时，需要先进行getColumnListRun
          isFirst.current = false
          // return new Promise((resolve, reject) => getColumnListRun(resolve, reject)).then(() => Promise.resolve(executeSql(tableConfigId, Object.assign({}, params, queryInitialValueParams.current))))
          return new Promise((resolve, reject) => getColumnListRun(resolve, reject)).then(() => Promise.resolve(executeSql(tableConfigId, Object.assign({}, params, queryInitialValueParams.current))))
        } else {
          return executeSql(tableConfigId, Object.assign({}, params, queryInitialValueParams.current))
        }
      }}
      rowClassName={(_, index) => "report-table-row" + (index % 2)}
      breadcrumbRoutes={[
        {
          path: '/report/report',
          breadcrumbName: '报表列表',
        },
        {
          path: '',
          breadcrumbName: '报表详情',
        }
      ]}
      searchOptionRender={({searchText, resetText}: any, {form}: any, dom: any[]) => {
        return dom.concat([
          <Button onClick={() => {
            // let params = searchForm.getFieldsValue();
            let params:any = queryInitialValueParams.current;
            // 去掉form.getFieldsValue()的undefined值
            let newParams: any = {};
            for (let key in params) {
              let value = params[key]
              if (value !== undefined) {
                newParams[key] = value
              }
            }
            // 合并参数
            // let lastParams: {} = Object.assign({}, requestParams, newParams);
            let lastParams: {} = newParams;
            // 参数转为get形式
            let paramString: any;
            for (let key in lastParams) {
              let value: any = lastParams[key]
              let valueString = "";
              if (value) {
                if (value.constructor === Array) {
                  // 处理参数为数组的情况
                  value.forEach((v, i) => {
                    try {
                      valueString = valueString + (i !== 0 ? "," : "") + v.format("YYYY-MM-DD HH:mm:ss")
                    } catch {
                      valueString = valueString + (i !== 0 ? "," : "") + v
                    }
                  })
                } else {
                  valueString = value;
                }
              }
              paramString = (paramString ? paramString : "") + key + "=" + valueString + "&"
            }
            paramString = (paramString ? paramString : "") + "tableConfigId=" + tableConfigId + "&reportId=" + reportId
            let serviceParams = getServiceParams();
            imitateAClick(serviceParams.mapping + serviceParams.apiPrefix + serviceParams.version + modulesUrl.reportReport + "/export?" + paramString, "test.xls")
          }}>导出</Button>
        ])
      }
      }
    />
  )
}

export default ReportDetails
